//给你一个链表，两两交换其中相邻的节点，并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题（即，只能进行节点交换）。 
//
// 
//
// 示例 1： 
//
// 
//输入：head = [1,2,3,4]
//输出：[2,1,4,3]
// 
//
// 示例 2： 
//
// 
//输入：head = []
//输出：[]
// 
//
// 示例 3： 
//
// 
//输入：head = [1]
//输出：[1]
// 
//
// 
//
// 提示： 
//
// 
// 链表中节点的数目在范围 [0, 100] 内 
// 0 <= Node.val <= 100 
// 
// Related Topics 递归 链表 
// 👍 1410 👎 0


package com.cjl.leetcode.editor.cn;
/**
 * [P24]_两两交换链表中的节点
 * @author cjl
 * @date 2022-06-01 23:03:50
 */
public class P24_SwapNodesInPairs{
      public static void main(String[] args) {
            //测试代码
           Solution solution = new P24_SwapNodesInPairs().new Solution();
          P24_SwapNodesInPairs.ListNode L5 = new P24_SwapNodesInPairs().new ListNode(5, null);

          P24_SwapNodesInPairs.ListNode L4 = new P24_SwapNodesInPairs().new ListNode(4, L5);
          P24_SwapNodesInPairs.ListNode L3 = new P24_SwapNodesInPairs().new ListNode(3, L4);

          P24_SwapNodesInPairs.ListNode L2 = new P24_SwapNodesInPairs().new ListNode(2, L3);
          P24_SwapNodesInPairs.ListNode L1 = new P24_SwapNodesInPairs().new ListNode(1, L2);
          P24_SwapNodesInPairs.ListNode result = solution.swapPairs(L1);
          while (null != result){
              System.out.println("args = " + result.val);
              result = result.next;
          }
      }
      //力扣代码
      //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if( null == head || null == head.next){
            return head;
        }
        ListNode L1 =new ListNode(); //哑节点
        L1.next = head;
        ListNode pre = L1;
        ListNode current = head;
        ListNode next = current.next;
        while (null != current && null != next){
            pre.next = current.next;
            current.next = next.next;
            next.next = current;
            pre = pre.next.next;
            current = current.next;
            if(null != current){
                next = current.next;
            }else{
                next = null;
            }
        }
        return L1.next;

    }
}
//leetcode submit region end(Prohibit modification and deletion)

    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
  }